﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace ddz_server
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("请输入端口号：[8541]");
            int port = 8541;
            string line = Console.ReadLine();
            if (line.Length > 0)
            {
                if (!Int32.TryParse(line, out port))
                {
                    Console.WriteLine("输入有误!按任意键退出");
                    Console.ReadKey();
                    return;
                }
            }
            Console.Write("请输入最大在线人数：[10]");
            line = Console.ReadLine();
            int maxOnline = 10;
            if (line.Length > 0)
            {
                if (!Int32.TryParse(line, out maxOnline))
                {

                    Console.WriteLine("输入有误!按任意键退出");
                    Console.ReadKey();
                    return;
                }
            }
            ServerMessage.init(maxOnline);
            Console.WriteLine("启动服务 ,port = {0}...", port);
            SocketServer server = new SocketServer(port);
            server.HandleServerStarted = new Action<SocketServer>(theServer => {
                Console.WriteLine("服务启动成功!!");
            });
            server.HandleNewClientConnected = ServerMessage.conn;
            server.HandleClientClose = ServerMessage.close;
            server.HandleException = server.HandleSendException = server.StartException = handleException;
            server.HandleRecMsg = ServerMessage.message;

            server.StartServer();
            Console.WriteLine("输入指令q退出");
            while (true)
            {
                line = Console.ReadLine();
                if (line == "q")
                {
                    break;
                }
                else if (line.Length == 0)
                {
                    continue;
                }
                else
                {
                    Console.WriteLine("未知的命令:" + line);
                }
            }
        }

        static void handleException(Exception e)
        {
            Console.WriteLine("系统异常:");
            Console.WriteLine(e.ToString());
        }

        
    }
}
